﻿using System.Threading.Tasks;
using MahApps.Metro.Controls;
using MahApps.Metro.Controls.Dialogs;
using MaxStoreErp.Core.Exceptions;
using MaxStoreErp.Core.Interfaces;
using Microsoft.Practices.Unity;

namespace MaxStoreErp.Core.Infrastructure
{
    public class MetroDialogMessage : IMessager
    {
        [Dependency]
        public IUnityContainer Container { get; set; }

        static BaseMetroDialog _dialog;

        public Task InfoMessageAsync(string message, string caption)
        {
            var shellWindow = GetMetroWindow();

            var mySettings = new MetroDialogSettings
            {
                AffirmativeButtonText = "ОК",
            };

            return shellWindow.ShowMessageAsync(caption, message,
                MessageDialogStyle.Affirmative, mySettings);
        }

        public async Task<MessageResult> QuestionMessageAsync(string message, string caption)
        {
            var shellWindow = GetMetroWindow();

            var mySettings = new MetroDialogSettings
            {
                AffirmativeButtonText = "ДА",
                NegativeButtonText = "НЕТ"
            };

             var result = await shellWindow.ShowMessageAsync(caption, message,
                MessageDialogStyle.AffirmativeAndNegative, mySettings);

            return result == MessageDialogResult.Affirmative ? MessageResult.Ok : MessageResult.No;
        }

        public Task CustomDialogAsync(object content)
        {
            var shellWindow = GetMetroWindow();
            _dialog = new SimpleDialog {DialogBody = content};

            return shellWindow.ShowMetroDialogAsync(_dialog);
        }

        public Task CloseCustomDialogAsync()
        {
            var shellWindow = GetMetroWindow();
            if (_dialog == null)
                return null;

            var result = shellWindow.HideMetroDialogAsync(_dialog);
            _dialog = null;
            return result;
        }

        MetroWindow GetMetroWindow()
        {
            var shellWindow = Container.Resolve<IShellWindow>().ShellView as MetroWindow;
            if (shellWindow == null)
                throw new ErpRuntimeException("Оболочка приложения не является окном Metro!");

            return shellWindow;
        }
    }
}
